from spider import Spider, SpiderItemType, SpiderSource, SpiderDanmaku, SpiderItem
from utils import get_image_path
from proxy import get_proxy_url
import requests
from cache import get_cache, set_cache
import xbmcaddon
import re
import json
import time

_ADDON = xbmcaddon.Addon()


class SpiderQQLive(Spider):

    def name(self):
        return 'QQ直播'

    def logo(self):
        return get_image_path('qq_live.png')

    def hide(self):
        return not _ADDON.getSettingBool('data_source_qq_live_switch')

    def is_searchable(self):
        return True

    def list_items(self, parent_item=None, page=1):
        if parent_item is None:
            r = requests.get('https://live.qq.com/api/live/index')
            data = r.json()['data']

            items = []
            for tag_id in data:
                tag = data[tag_id]
                items.append(
                    SpiderItem(
                        type=SpiderItemType.Directory,
                        id=tag['short_name'],
                        name=tag['tag_name'],
                        params={
                            'type': 'category',
                        },
                    ))
            return items, False
        elif parent_item['params']['type'] == 'category':
            r = requests.get(
                'https://live.qq.com/api/live/vlist',
                params={
                    'shortName': parent_item['id'],
                    'page': page,
                    'page_size': 60,
                },
            )
            data = r.json()['data']

            items = []
            for room in data['result']:
                items.append(
                    SpiderItem(type=SpiderItemType.File,
                               id=room['room_id'],
                               name='{} - {}'.format(
                                   room['room_name'],
                                   room['nickname'],
                               ),
                               description='主播: {}\n分类: {}'.format(
                                   room['nickname'],
                                   room['game_name'],
                               ),
                               cover=room['room_src'],
                               sources=[
                                   SpiderSource(
                                       room['room_id'],
                                       {
                                           'id': room['room_id'],
                                       },
                                   )
                               ]))

            return items, len(items) >= 60
        else:
            return [], False

    def resolve_play_url(self, source_params):
        return get_proxy_url(
            SpiderQQLive.__name__,
            self.proxy_m3u8.__name__,
            source_params,
        )

    def search(self, keyword):
        r = requests.get(
            'https://live.qq.com/api/info/search/',
            params={
                'keyword': keyword,
            },
        )
        data = r.json()

        items = []
        for room in data['room']:
            items.append(
                SpiderItem(type=SpiderItemType.File,
                           id=room['room_id'],
                           name='{} - {}'.format(
                               room['room_name'],
                               room['nickname'],
                           ),
                           description='主播: {}\n分类: {}'.format(
                               room['nickname'],
                               room['game_name'],
                           ),
                           cover=room['room_src'],
                           sources=[
                               SpiderSource(
                                   room['room_id'],
                                   {
                                       'id': room['room_id'],
                                   },
                               )
                           ]))

        return items

    def proxy_m3u8(self, ctx, params):
        id = params['id']
        url = ''

        key = 'qq_live_m3u8'
        data = get_cache(key)
        if data:
            data = json.loads(data)
            if data['id'] == id and data['expires_at'] >= int(time.time()):
                url = data['url']

        if len(url) == 0:
            r = requests.get('https://m.live.qq.com/{}'.format(id))
            m = re.search(r"ROOM_INFO = (.*);<", r.text, re.MULTILINE)
            data = json.loads(m.group(1))
            url = data['hls_url']
            set_cache(
                key,
                json.dumps({
                    'id': id,
                    'url': url,
                    'expires_at': int(time.time() + 600),
                }))

        self.proxy(ctx, url)
